import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/server/api/user_api.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/widget_utils.dart';

import '../../../widgets/base/qkd_text.dart';

enum _VerifyState { not, process, done }

class MyAccountCertificationPage extends StatefulWidget {
  const MyAccountCertificationPage({super.key});

  @override
  State<MyAccountCertificationPage> createState() =>
      _MyAccountCertificationPageState();
}

class _MyAccountCertificationPageState
    extends State<MyAccountCertificationPage> {
  bool get verified => false;

  final tname = TextEditingController();
  final tID = TextEditingController();
  final tcode = TextEditingController();

  String phone = User.info?.phone ?? "";
  String? name = User.info?.realName;
  // ignore: non_constant_identifier_names
  String? ID = User.info?.cardId;

  _VerifyState get state =>
      User.isPersonVerified ? _VerifyState.done : _VerifyState.not;

  Widget _makeInput(String hint, {TextEditingController? tec}) => TextFormField(
        controller: tec,
        onChanged: (value) {
          checkValid();
        },
        decoration: InputDecoration(
            border: InputBorder.none,
            hintText: hint,
            hintStyle: const TextStyle(fontSize: 14, color: Colours.grey99)),
      );

  Widget get inputName => _makeInput("请输入姓名", tec: tname);
  Widget get inputID => _makeInput("请输入身份证", tec: tID);
  Widget get inputCode => _makeInput("请输入验证码", tec: tcode);

  static DateTime smsTime = DateTime.fromMicrosecondsSinceEpoch(0);
  Timer? t;
  int get smsSecond => DateTime.now().difference(smsTime).inSeconds;

  bool valid = false;
  checkValid() {
    final idno = RegExp(
        r'^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$');
    valid = idno.hasMatch(tID.text) && tname.text.isNotEmpty && tcode.text.isNotEmpty;
    update();
  }

  @override
  void dispose() {
    t?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    User.fetchUserInfo();
    t = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (DateTime.now().difference(smsTime).inSeconds < 120) {
        update();
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Widget body;
    switch (state) {
      case _VerifyState.not:
        body = _verifyColumn();
        break;
      default:
        body = _stateColumn(state);
    }

    return Scaffold(
      appBar: Styles.appBar(
          title: const QkdText("实名认证"), backgroundColor: Colours.transparent),
      backgroundColor: Colours.scaffoldBg,
      body: body.tap(() {
        FocusScope.of(context).unfocus();
      }),
    );
  }

  Widget _stateColumn(_VerifyState state) => Column(
        children: [
          const SizedBox(height: 8),
          Styles.card(
            height: 194,
            margin: const EdgeInsets.symmetric(horizontal: 8),
            color: Colors.white,
            alignment: Alignment.center,
            child: DefaultTextStyle(
              style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colours.text),
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        height: 52,
                        width: 52,
                        decoration: const BoxDecoration(
                            shape: BoxShape.circle, color: Colours.main),
                        child: const Icon(Icons.done_sharp,
                            color: Colours.white, size: 36)),
                    const SizedBox(
                      height: 20,
                    ),
                    if (state == _VerifyState.done) QkdText("已完成实名认证"),
                    if (state == _VerifyState.process) QkdText("审核中")
                  ]),
            ),
          ),
          const SizedBox(height: 8),
          _whiteBox(Column(
            children: [
              _cell("姓名", tail: QkdText(name ?? "")),
              _divider(),
              _cell("身份证号", tail: QkdText(ID ?? "")),
            ],
          ))
        ],
      );

  Widget _verifyColumn() {
    return Column(
      children: [
        const SizedBox(height: 8),
        _whiteBox(Column(
          children: [
            _cell("姓名", tail: inputName),
            const Divider(indent: 16, height: 0.5, color: Colours.greyEE),
            _cell("身份证号", tail: inputID),
          ],
        )),
        const SizedBox(height: 8),
        _whiteBox(Column(
          children: [
            _cell("手机号",
                tail: Row(
                  children: [
                    QkdText(
                        '${phone.characters.take(3)}*****${phone.characters.takeLast(4)}'),
                    const Spacer(),
                    Container(
                      width: 81,
                      height: 24,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(2),
                          color: Colours.redFFEEEE,
                          border: Border.all(color: Colours.main)),
                      child: QkdText(
                        smsSecond >= 60 ? '获取验证码' : "${60 - smsSecond}秒后",
                        color: Colours.main, fontSize: 13
                      ),
                    ).tap(() {
                      if (smsSecond < 60) {
                        return;
                      }
                      UserApi.sendSms(phone, 3).then((value) {
                        smsTime = DateTime.now();
                      });
                    })
                  ],
                )),
            const Divider(indent: 16, height: 0.5, color: Colours.greyEE),
            _cell("验证码", tail: inputCode),
          ],
        )),
        const SizedBox(height: 50),
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 8),
          height: 44,
          decoration: BoxDecoration(
              color: valid ? Colours.main : Colours.main.withOpacity(0.5),
              borderRadius: BorderRadius.circular(8)),
          alignment: Alignment.center,
          child: const QkdText(
            "确认提交",
            color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500
          ),
        ).tap(() {
          UserApi.authCheckName(tID.text, tname.text, tcode.text)
              .then((value) async {
            if (value.data['d']) {
              await Future.delayed(const Duration(milliseconds: 100));
              User.fetchUserInfo().then((value) {
                name = User.info?.realName ?? tname.text;
                ID = User.info?.cardId ?? tID.text;
                update();
              });
            } else {
              WidgetUtils.alertQuery('信息填写有误，请核对后重新提交');
            }
          });
        }),
        Container(height: 30),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              "认证提示：",
              style: TextStyle(fontSize: 12,color: Colours.grey66)
            ),
            Container(height: 4),
            const Text(
              "1.身份证号仅用于实名认证使用，平台会委托第三方查询、 核对您的身份真实性。\n2.每个证件只能绑定一个账号，已被绑定的证件，无法再次与其他账号绑定；\n3.为保障账户以及资金的安全，手机号实名信息需与身份信息保持一致，且手机号不能是虚拟卡、流量卡、亲情卡、副卡。",
              style: TextStyle(fontSize: 12,height: 1.2,color: Colours.grey99),
            )
          ],
        ).paddingSymmetric(horizontal: 8)
      ],
    );
  }

  Widget _whiteBox(Widget child) => Styles.card(
        color: Colors.white,
        margin: EdgeInsets.symmetric(horizontal: 8),
        child: child,
      );

  Widget _divider() =>
      const Divider(indent: 16, height: 0.5, color: Colours.greyEE);

  Widget _cell(String title, {required Widget tail}) {
    return Container(
      height: 52,
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          QkdText(title).sized(width: 74),
          // tail
          Expanded(child: tail)
        ],
      ),
    );
  }
}
